package com.mty.service;

import com.mty.dao.PermissonDao;
import com.mty.dao.UsersDao;
import com.mty.entity.Permisson;
import com.mty.entity.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ：Teacher马（2508531326@qq.com）
 * @date ：Created in 2022/11/1 15:44
 * @description：
 * @modified By：
 * @version:
 */
@Service
public class MySecurity implements UserDetailsService {


    @Autowired
    private UsersDao usersDao;
    @Autowired
    private PermissonDao permissonDao;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users users = usersDao.selectByUsername(username);
        if (users != null) {
            //该用户具有的权限
            Collection<GrantedAuthority> authorities = new ArrayList<>();
            //根据用户id查询该用户具有的权限。
//            List<Permission> permissions = permissionDao.findByUserid(users.getUserid());

            List<Permisson> permissions = permissonDao.findByUserid(users.getUserid());
            //把上面的权限封装authorities中----jdk1.8 Stream流--
            authorities = permissions.stream()
                    .map(item -> new SimpleGrantedAuthority(item.getPercode()))
                    .collect(Collectors.toList());

//            for(Permission item:permissions){
//                SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(item.getPercode());
//                authorities.add(simpleGrantedAuthority);
//            }

            User user = new User(username, users.getUserpwd(), authorities);
            return user;
        }
        return null;
    }
}